package com.git.bds.mr.login.controller;

import cn.hutool.core.util.RandomUtil;
import com.git.bds.mr.framework.redis.constant.RedisConstants;
import com.git.bds.mr.framework.redis.util.RedisUtils;
import com.git.bds.mr.result.R;
import com.git.bds.mr.sms.core.TxSmsTemplate;
import com.git.bds.mr.util.validate.phone.Phone;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;

/**
 * @author 成大事
 * @since 2022/3/5 10:41
 */
@Api(tags = "手机验证码")
@Slf4j
@Validated
@RestController
@RequestMapping("/captcha")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class SMSController {

    private final TxSmsTemplate txSmsTemplate;

    private final RedisUtils redisUtil;

    /**
     * 腾讯云发送短信测试
     *
     * @param phone 手机号
     */
    @ApiOperation("发送验证码")
    @PostMapping("/sendSmsCaptcha")
    public R<Boolean> sendSmsCaptcha(
            @ApiParam(value = "手机号", required = true) @RequestParam("tel") @NotBlank(message = "手机号不能为空") @Phone String phone) {

        // 参数1: 手机号(正文模板中的参数{1})
        // 参数2: 验证码(正文模板中的参数{2})
        String random = RandomUtil.randomNumbers(6);

        String msg = txSmsTemplate.sendMesModel(phone, random);

        log.info(msg);

        // Msg不为null 发送成功
        // Msg为null  发送失败
        String redisKey = RedisConstants.REGISTER_PHONE_KEY + phone;
        redisUtil.set(redisKey,random,60 * 10);
        return R.ok();
    }

}
